package com.eostoken.eos_wallet.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.ValueCallback;
import android.widget.EditText;

import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.eostoken.eos_wallet.R;
import com.eostoken.eos_wallet.base.BaseActivity;
import com.eostoken.eos_wallet.bean.CreateAccountMode;
import com.eostoken.eos_wallet.bean.CreateWalletMode;
import com.eostoken.eos_wallet.db.MgpWallet;
import com.eostoken.eos_wallet.helper.DialogConfirmListener;
import com.eostoken.eos_wallet.helper.DialogHelper;
import com.eostoken.eos_wallet.mvp.callback.CommonCallback;
import com.eostoken.eos_wallet.net.common.BaseUrlUtils;
import com.eostoken.eos_wallet.utils.Constants;
import com.eostoken.eos_wallet.utils.WalletUtils;
import com.fredy.mvp.BasePresenter;
import com.fredy.mvp.BaseView;
import com.fredy.mvp.Model;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import wendu.webviewjavascriptbridge.WVJBWebView;

import static com.eostoken.eos_wallet.utils.Constants.EXTRA_CREATE_ACCOUNT_DATA;


public class AssistCreateActivity extends BaseActivity {
    @BindView(R.id.webview)
    WVJBWebView webview;
    @BindView(R.id.topbar)
    QMUITopBarLayout topbar;
    @BindView(R.id.logoIv)
    AppCompatImageView logoIv;
    @BindView(R.id.creatorTv)
    AppCompatTextView creatorTv;
    @BindView(R.id.accountNameTv)
    AppCompatTextView accountNameTv;
    @BindView(R.id.activePublickeyTv)
    AppCompatTextView activePublickeyTv;
    @BindView(R.id.ownerPublickeyTv)
    AppCompatTextView ownerPublickeyTv;
    @BindView(R.id.RAMTv)
    AppCompatTextView RAMTv;
    @BindView(R.id.CPUTv)
    AppCompatTextView CPUTv;
    @BindView(R.id.NETTv)
    AppCompatTextView NETTv;
    @BindView(R.id.immediatelyCreateBtn)
    QMUIRoundButton immediatelyCreateBtn;

    private final static String url = "file:///android_asset/EOSWeb.html";//"file:///android_asset/" + "testss.html";//"EOSWeb.html";
    private String assistCreateWalletData;
    private CreateAccountMode createAccountMode;
    private String creator;
    private String private_key;
    private String account;
    private long buy_ram_bytes;
    private String stake_net_quantity;
    private String stake_cpu_quantity;
    private String active_pubkey;
    private String owner_pubkey;
    private String ep = BaseUrlUtils.getEOSBaseUrl();
    private QMUIDialog qmuiDialog;
    private QMUIDialog mQMUIDialog;
    private MgpWallet wallet;
    private String json;

    @Override
    protected void initData() {
        Bundle bundle = getIntent().getExtras();
        assistCreateWalletData = bundle.getString(EXTRA_CREATE_ACCOUNT_DATA, "");
        createAccountMode = GsonUtils.fromJson(assistCreateWalletData, CreateAccountMode.class);
        creator = WalletUtils.getCurrentAccountName();
        private_key = WalletUtils.getCurrentPrivatekey();
        WalletUtils.queryWallet(AssistCreateActivity.this, creator, new CommonCallback() {
            @Override
            public void onSuccess(Object data, String successMsg, int responseSuccessCode) {
                List<MgpWallet> walletList = (List<MgpWallet>) data;
                wallet = walletList.get(0);
            }

            @Override
            public void onFailure(String msg, int responseFailCode) {
            }
        });
        if (ObjectUtils.isEmpty(creator) || ObjectUtils.isEmpty(private_key)) {
            DialogHelper.showLongMessageDialog(AssistCreateActivity.this, getString(R.string.str_hint),
                    getString(R.string.str_active_error_msg), "", getString(R.string.str_to_login), null, new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            Intent intent = new Intent(AssistCreateActivity.this, AddWalletActivity.class);
                            ActivityUtils.startActivity(intent);
                            dialog.dismiss();
                        }
                    }).show();
        }
    }

    @Override
    public void initView() {
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.app_color_blue));
        BarUtils.setStatusBarLightMode(this, false);
        topbar.setTitle(StringUtils.getString(R.string.str_assist_create));
        topbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        webview.loadUrl(url);
        account = createAccountMode.getAccount();
        creatorTv.setText(creator);
        accountNameTv.setText(account);
        active_pubkey = createAccountMode.getActive();
        activePublickeyTv.setText(active_pubkey);
        owner_pubkey = createAccountMode.getOwner();
        ownerPublickeyTv.setText(owner_pubkey);
        buy_ram_bytes = 4300;
        RAMTv.setText(buy_ram_bytes + "");
        stake_net_quantity = "0.2500 " + Constants.MGP_SYMBOL;
        NETTv.setText(stake_net_quantity);
        stake_cpu_quantity = "0.0400 " + Constants.MGP_SYMBOL;
        CPUTv.setText(stake_cpu_quantity);
        webview.setWebContentsDebuggingEnabled(true);
        if (mQMUIDialog == null) {
            mQMUIDialog = DialogHelper.showEditTextDialog(this, getString(R.string.str_password_authentification),
                    getString(R.string.str_enter_password), getString(android.R.string.ok), getString(android.R.string.cancel), listener, true);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("account", account);
        map.put("creator", creator);
        map.put("private_key", private_key);
        map.put("buy_ram_bytes", buy_ram_bytes);
        map.put("stake_net_quantity", stake_net_quantity);
        map.put("stake_cpu_quantity", stake_cpu_quantity);
        map.put("active_pubkey", active_pubkey);
        map.put("owner_pubkey", owner_pubkey);
        map.put("ep", ep);
        json = JSON.toJSONString(map);
    }

    @Override
    public boolean isShowState() {
        return true;
    }

    DialogConfirmListener listener = new DialogConfirmListener() {
        @Override
        public void onClick(QMUIDialog dialog, View view, int index) {
            EditText editText = ((EditText) view);
            String text = editText.getText().toString().trim();
            if (ObjectUtils.equals(text, wallet.getWalletPassword())) {
                createAccount(json);
            }
            editText.setText("");
            dialog.dismiss();
        }
    };

    @Override
    public int getContentView() {
        return R.layout.fragment_assist_create;
    }

    @Override
    public Model createModel() {
        return null;
    }

    @Override
    public BaseView createView() {
        return null;
    }

    @Override
    public BasePresenter createPresenter() {
        return null;
    }

    @Override
    public void finishRefresh() {

    }

    @OnClick(R.id.immediatelyCreateBtn)
    public void onViewClicked() {
        mQMUIDialog.show();
    }

    private void createAccount(String json) {
        webview.callHandler("createAccount", json, new WVJBWebView.WVJBResponseCallback() {
            @Override
            public void onResult(Object data) {
                String msg;
                if (ObjectUtils.equals("succeed", data.toString())) {
                    msg = getString(R.string.str_wallet_activate_succeed);
                } else {
                    msg = getString(R.string.str_wallet_activate_fail) + "\n" + data.toString();
                }
                dialog(msg);
            }
        });
    }

    private void dialog(String msg) {
        qmuiDialog = DialogHelper.showLongMessageDialog(AssistCreateActivity.this, getString(R.string.str_prompt_message), msg, "", getString(android.R.string.ok), null,
                new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        finish();
                    }
                });
        qmuiDialog.show();
    }

}

